package com.stx.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stx.common.Bcrypts;
import com.stx.common.Result;
import com.stx.exception.CustomException;
import com.stx.exception.CustomExceptionUtils;
import com.stx.mapper.JudgeMapper;
import com.stx.pojo.Judge;
import com.stx.pojo.ParamChangePwd;
import com.stx.pojo.Params;
import com.stx.pojo.Record;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class JudgeService {

    @Autowired
    private JudgeMapper judgeMapper;

    public List<Judge> getjudge() {
        return judgeMapper.selectjudge();
    }

    public void add(Judge judge) {
        //1.用户名一定要有，否则不让新增（后面需要用户名登录）
        if(judge.getJudUsername() == null || "".equals(judge.getJudUsername())) {
            throw new CustomException("用户名不能为空");
        }
        //2.进行重复性判断，同一名字的管理员不允许重复新增
        //只要根据用户名去数据查询一下就可以
        Judge user = judgeMapper.findByName(judge.getJudUsername());
        if(user != null) {
            //说明已经有了，这里我们就要提示前台不允许新增了
            throw new CustomException("该用户名已存在，请勿重复添加");
        }
        if(judge.getJudPassword() == null || "".equals(judge.getJudPassword())) {
            judge.setJudPassword("123456");
        }
        if(judge.getJudDate() == null) {
            judge.setJudDate(LocalDateTime.now());
        }
        judgeMapper.add(judge);
    }

    public void update(Judge judge) {
        judge.setJudDate(LocalDateTime.now());
        judgeMapper.updateID(judge);
    }

    public void delete(Integer id) {
         judgeMapper.deleteID(id);
    }

    public Judge login(Judge judge) {
        Judge user = judgeMapper.findByNameAndPassword(judge);
        if(user == null) {
            throw new CustomExceptionUtils("用户或密码输入错误");
        }
        return user;
    }

    public List<Judge> findBySearch(Params params) {
        if (params == null || params.getName() == null || "".equals(params.getName())) {
            throw new CustomException("搜索条件不能为空");
        }
        return judgeMapper.findBySearch(params);
    }

    public Map<Integer, String> listJudge() {
        List<Judge> judges = judgeMapper.selectList(null);
        Map<Integer, String> collect = judges.stream().collect(Collectors.toMap(Judge::getId, Judge::getJudName));
        return collect;
    }

    public Page<Judge> find(Object userName, Object judRole, Integer currentPage, Integer pageSize) {
        //int currentPage = 1;
        //int pageSize = 10;
        System.out.println("name=" + userName);
        System.out.println("name=" + judRole);
        LambdaQueryWrapper<Judge> wrapper = new LambdaQueryWrapper<>();
        //这里字符串有2种状态
        wrapper.like(userName!=null, Judge::getJudUsername, userName);
        wrapper.like(judRole!=null, Judge::getJudRole, judRole);
        /*wrapper.eq(userName!=null, Judge::getJudUsername, userName);
        wrapper.eq(judName!=null, Judge::getJudName, judName);*/
        //创建分页条件
        Page<Judge> page = new Page<>(currentPage, pageSize);
        //执行分页查询（分页结果）
        Page<Judge> resultPage = judgeMapper.selectPage(page, wrapper);
        //当前页数据
        List<Judge> records = resultPage.getRecords();
        //总记录数
        long total = resultPage.getTotal();
        //总页数
        long pages = resultPage.getPages();
        com.stx.common.Page<Record> pageFind = new com.stx.common.Page<>();
        pageFind.setTotal(total);
        pageFind.setPages(pages);
        return page;
    }

    public Result changePassword(ParamChangePwd pcp) {
        Judge judge = new Judge();
        judge.setJudUsername(pcp.getAccount());
        judge.setJudPassword(pcp.getOldPassword());
        // 1.检查旧密码是否正确
        Judge user = judgeMapper.findByNameAndPassword(judge);
        if(user == null) {
           return  Result.error("旧密码错误");
        }
        // 验证状态是否正常 只要不是-1就行   -1 删除； 0未激活 ；1正常； 2从来没登录过
        if(judge.getJudState() == -1) {
            return Result.error("用户状态异常");
        }
        // 身份验证成功，允许修改密码
        // 1.对密码进行加密
        String pwd  =  Bcrypts.hashPw(pcp.getNewPassword());
        // 2.存储新密码 并 更新用户的状态status==1
        judge.setId(user.getId());
        judge.setJudPassword(pwd);
        judge.setJudState(1);
        int result = judgeMapper.updateById(judge);
        if(result == 1) {
            return Result.success();
        } else {
            return Result.error("修改密码失败");
        }
    }
}
